﻿ (function($){
 	$.FillOptionsRenderer = function(opts) {
 		this.opts = opts;
 	}
 	
 	$.extend($.FillOptionsRenderer.prototype, {
 		getDatas:function(url) {
 			$.ajaxSetup({async:false});
		    var datas;
		    if(this.opts.type == "xml") {
		        $.get(url,function(xml){datas=xml;});            
		    } else {
		        $.getJSON(url,function(json){datas=json;});
		    }
		    if(datas == undefined) {
				alert("no datas");
				return;
			}
			datas = eval("datas." + this.opts.jsonData);
		    return datas;
 		},
 		addOptions:function(select, datas) {        
		    var option;
		    var opts = this.opts;
		    option = new Option("-请选择-", "-1");
            select.options.add(option);
		    if(opts.type == "xml") {
		        $(text,datas).each(function(i){            
		            option = new Option($(this).text(),$($(value,datas)[i]).text());
		            //if(i==opts.selected)option.selected=true;
		            select.options.add(option);
		        });
		    } else {
		        $.each(datas,function(i,n){
		            option = new Option(eval("n." + opts.text),eval("n." + opts.value));
		            //if(i==opts.selected)option.selected=true;
		            select.options.add(option);
		        });
		    }
		}
 	});
 	 $.fn.fillOptions = function(url, opts){
		// Initialize options with default values
		opts = jQuery.extend({
			type:"json",
			jsonData:"jsonData",
			selected:0,
			keep:false,
			text:"name",
			value:"id"
		},opts||{});
		if(url.length == 0) throw "request url is required";
		url = url + "&temp=" + new Date();
		var renderer = new $.FillOptionsRenderer(opts);
		var datas = renderer.getDatas(url);
		if (datas) {
			this.each(function(){
		        if(this.tagName == "SELECT") {
		            var select = this;
		            if(!opts.keep)$(select).html("");
		            renderer.addOptions(select,datas);
		        }
		    });
		}
 	 }
})(jQuery);